package com.meatball.game.websocket

import com.meatball.game.factory.RoomManagerFactory
import com.meatball.game.service.AiGameService
import com.meatball.game.service.RoomCacheService
import org.slf4j.LoggerFactory
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.web.socket.CloseStatus
import org.springframework.web.socket.TextMessage
import org.springframework.web.socket.WebSocketSession
import org.springframework.web.socket.handler.TextWebSocketHandler

class WebsocketHandler(
        aiGameService: AiGameService,
        stringRedisTemplate: StringRedisTemplate,
        roomCacheService: RoomCacheService
) : TextWebSocketHandler() {
    // 存储所有的WebSocket会话
    private val roomManager = RoomManagerFactory(aiGameService, stringRedisTemplate, roomCacheService)
            .createRoomManager()

    /**
     * TODO 处理文本消息，接收到的消息将被解析为ChatMessage对象，然后广播给所有已连接的客户端
     *
     * @param session
     * @param message
     */
    override fun handleTextMessage(session: WebSocketSession, message: TextMessage) {
        roomManager.sendMessage(session, message.payload)
    }

    /**
     * TODO 当新的WebSocket会话建立时，将其添加到sessions集合中
     *
     * @param session
     */
    override fun afterConnectionEstablished(session: WebSocketSession) {
        roomManager.joinRoom(session)
    }

    /**
     * TODO 当WebSocket会话关闭时，将其从sessions集合中移除
     *
     * @param session
     * @param status
     */
    override fun afterConnectionClosed(session: WebSocketSession, status: CloseStatus) {
        roomManager.leaveRoom(session)
    }
}